<?php

namespace app\lib;

use AlibabaCloud\SDK\Bailian\V20230601\Bailian;
use AlibabaCloud\SDK\Bailian\V20230601\Models\CreateTokenRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;
use Exception;
use AlibabaCloud\SDK\Bailian\V20230601\Models\GetPromptRequest;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

class AiInfo
{

    public function __construct()
    {
        $path = app()->getAppPath() . 'bailian/autoload.php';
        if (file_exists($path)) {
            require_once $path;
        }
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Bailian Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/bailian
        $config->endpoint = "bailian.cn-beijing.aliyuncs.com";
        return new Bailian($config);
    }
//e645e6a2062043f198decd7c1b5402a8
    public function getToken()
    {
        // 引入文件
        $accessKeyId = 'LTAI5tLAZdDAmP6sG9LgXM7T';
        $accessKeySecret = 'UxsgWdxuPD5ZbFHMZ6KTnEvCFGkdyB';
        $agentKey = 'bef69dc66a494723bc16266771621be0_p_efm';
// 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用，仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html
        $client = self::createClient($accessKeyId, $accessKeySecret);
        $createTokenRequest = new CreateTokenRequest([
            "agentKey" => $agentKey
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            return $client->createTokenWithOptions($createTokenRequest, $runtime);

        }
        catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 错误 message
            var_dump($error->message);
            // 诊断地址
            var_dump($error->data["Recommend"]);
            Utils::assertAsString($error->message);
        }
    }

    public function create()
    {
        // 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用，仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html
        $accessKeyId = 'LTAI5tLAZdDAmP6sG9LgXM7T';
        $accessKeySecret = 'UxsgWdxuPD5ZbFHMZ6KTnEvCFGkdyB';
        $agentKey = 'bef69dc66a494723bc16266771621be0_p_efm';
        $client = self::createClient($accessKeyId, $accessKeySecret);
        $getPromptRequest = new GetPromptRequest([
            "promptId" => "marketCopy",
            "agentKey" => $agentKey,
            "vars" => "{\"platform\":\"小红书\",\"topic\":\"秋天到了需要推荐一些好看又百搭的女款衣服\",\"num1\":\"10\"}"
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $info = $client->getPromptWithOptions($getPromptRequest, $runtime);
            var_dump($info->body->data->promptContent);
        }
        catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 错误 message
            var_dump($error->message);
            // 诊断地址
            var_dump($error->data["Recommend"]);
            Utils::assertAsString($error->message);
        }
    }

    public function info()
    {
       $tokenEntity = $this->getToken();
//        var_dump($tokenEntity->body);die();
       $client = new Client();
       $data = $client->post('https://bailian.aliyuncs.com/v2/app/completions', [
           RequestOptions::HEADERS => [
               'Authorization' => 'Bearer ' . $tokenEntity->body->data->token
           ],
           RequestOptions::JSON => [
               'AppId' => '3030dea24fa64da8b5d385c3834a3ce7',
               'Prompt' => '你是一名专业的小红书爆款营销文案专家。请以秋天到了需要推荐一些好看又百搭的女款衣服为主题，创作营销内容。包括标题、正文。至少包含10不同emoji表情，并给出热门推荐标签。',
               'RequestId' => $tokenEntity->body->requestId
           ]
       ]);
       var_dump($data->getBody()->getContents());
    }
}